<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>T4模版生成EF实体 | JiangKunYun&#39;s Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
    <meta name="keywords" content="熊猫不是猫,熊猫不是猫's Blog" />
  
  <meta name="description" content="T4(Text Template Transformation Toolkit)是微软官方在 VisualStudio 2008 中开始使用的代码生成引擎。在 VS 中只要与代码生成相关的场景基本上都能找 T4 的身影，比如 MVC 的视图模板，Entity Framwork 的 DataContext 模板等等。">
<meta property="og:type" content="article">
<meta property="og:title" content="T4模版生成EF实体">
<meta property="og:url" content="http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/index.html">
<meta property="og:site_name" content="JiangKunYun&#39;s Blog">
<meta property="og:description" content="T4(Text Template Transformation Toolkit)是微软官方在 VisualStudio 2008 中开始使用的代码生成引擎。在 VS 中只要与代码生成相关的场景基本上都能找 T4 的身影，比如 MVC 的视图模板，Entity Framwork 的 DataContext 模板等等。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/T4%E6%A8%A1%E6%9D%BF%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84.png">
<meta property="og:image" content="http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/%E4%BB%A3%E7%A0%81%E6%95%88%E6%9E%9C.png">
<meta property="article:published_time" content="2021-04-07T08:16:50.000Z">
<meta property="article:modified_time" content="2021-04-07T08:16:50.000Z">
<meta property="article:author" content="jiangkunyun">
<meta property="article:tag" content="T4">
<meta property="article:tag" content="EF">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/T4%E6%A8%A1%E6%9D%BF%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84.png">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>

  

  
  

<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
      <header id="header">
    <div id="banner"></div>
    <div id="header-outer">
        <div id="header-menu" class="header-menu-pos animated">
            <div class="header-menu-container">
                <a href="/" class="left">
                    <span class="site-title">熊猫不是猫的博客</span>
                </a>
                <nav id="header-menu-nav" class="right">
                    
                    <a  href="/">
                        <i class="fa fa-home"></i>
                        <span>首页</span>
                    </a>
                    
                    <a  href="/archives">
                        <i class="fa fa-archive"></i>
                        <span>归档</span>
                    </a>
                    
                    <a  href="/about">
                        <i class="fa fa-user"></i>
                        <span>关于</span>
                    </a>
                    
                </nav>
                <a class="mobile-header-menu-button">
                    <i class="fa fa-bars"></i>
                </a>
            </div>
        </div>
        <div id="header-row">
            <div id="logo">
                <a href="/">
                    <img src="/images/mylogo.png" alt="logo">
                </a>
            </div>
            <div class="header-info">
                <div id="header-title">
                    
                    <h2>
                        熊猫不是猫的博客
                    </h2>
                    
                </div>
                <div id="header-description">
                    
                    <h3>
                        一个专注 WEB 开发的技术博客
                    </h3>
                    
                </div>
            </div>
            <nav class="header-nav">
                <div class="social">
                    
                        <a title="JiangkunYun" target="_blank" href="//jiangkunyun.gitee.io/">
                            <i class="fa fa-home fa-2x"></i></a>
                    
                        <a title="Github" target="_blank" href="//github.com/jiangkunyun">
                            <i class="fa fa-github fa-2x"></i></a>
                    
                        <a title="Gitee" target="_blank" href="//gitee.com/jiangkunyun">
                            <i class="fa fa-git fa-2x"></i></a>
                    
                </div>
            </nav>
        </div>
    </div>
</header>
      <div class="outer">
        <section id="main" class="body-wrap"><article id="post-T4模版生成EF实体" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="post-title" itemprop="name">
      T4模版生成EF实体
    </h1>
    <div class="post-title-bar">
      <ul>
          
              <li>
                  <i class="fa fa-book"></i>
                  
                      <a href="/categories/模版引擎/">模版引擎</a>
                  
                      <a href="/categories/T4/">T4</a>
                  
              </li>
          
        <li>
          <i class="fa fa-calendar"></i>  2021-04-07
        </li>
        <li>
          <i class="fa fa-eye"></i>
          <span id="busuanzi_value_page_pv"></span>
        </li>
      </ul>
    </div>
  

          
      </header>
    
    <div class="article-entry post-content" itemprop="articleBody">
      
            
            <p>T4(Text Template Transformation Toolkit)是微软官方在 VisualStudio 2008 中开始使用的代码生成引擎。<br>在 VS 中只要与代码生成相关的场景基本上都能找 T4 的身影，比如 MVC 的视图模板，Entity Framwork 的 DataContext 模板等等。</p>
<span id="more"></span>

<h3 id="T4-模版引擎之基础入门"><a href="#T4-模版引擎之基础入门" class="headerlink" title="T4 模版引擎之基础入门"></a>T4 模版引擎之基础入门</h3><p>这里推荐 2 篇大神写的教程：</p>
<ol>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/lzrabbit/archive/2012/07/15/2591085.html">T4 模版引擎之基础入门</a></li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/dataadapter/p/3844394.html">用 T4 Template 生成代码</a></li>
</ol>
<h3 id="T4-代码生成-EF-实体"><a href="#T4-代码生成-EF-实体" class="headerlink" title="T4 代码生成 EF 实体"></a>T4 代码生成 EF 实体</h3><h4 id="项目结构"><a href="#项目结构" class="headerlink" title="项目结构"></a>项目结构</h4><p><img src="/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/T4%E6%A8%A1%E6%9D%BF%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84.png" alt="项目目录"></p>
<h4 id="DBCommon-ttinclude"><a href="#DBCommon-ttinclude" class="headerlink" title="DBCommon.ttinclude"></a>DBCommon.ttinclude</h4><p>定义各个数据库表和列的公共字段实体，还有一些公用方法。</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;#@ assembly name&#x3D;&quot;System.Core&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.xml&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Collections.Generic&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data.SqlClient&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Linq&quot;#&gt;
&lt;#+
    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 表
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public class DBTable
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 表名
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string TableName &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; （程序）表名
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string Name &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 备注
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string Remark &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 列
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public List&lt;DBColumn&gt; Columns &#123; get; set; &#125;
    &#125;

    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 列
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public class DBColumn
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 表名
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string TableName &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 列名
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string ColumnName &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; （程序）列名
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string Name &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; Sql数据类型
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string SqlType &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 数据类型
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string Type &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 字段序号
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public int Colorder &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 标识
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public bool IsIdentity &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 是否为主键
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public bool IsKey &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 长度
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public int Length &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 小数位数
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
		public int DecimalDigit &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 允许空
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public bool IsNull &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 默认值
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string DefaultValue &#123; get; set; &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 备注
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public string Remark &#123; get; set; &#125;
    &#125;

    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 公用方法
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public class DBCommon
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 清除前缀
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;str&quot;&gt;&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;prefix&quot;&gt;前缀&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        public string ClearPrefix(string str, string prefix)
        &#123;
            if (str.IndexOf(prefix) &#x3D;&#x3D; 0)
            &#123;
                return str.Substring(prefix.Length, str.Length - prefix.Length);
            &#125;
            return str;
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 首字母大写
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;str&quot;&gt;&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
		public string FirstToUpper(String str)
        &#123;
            if (str.Length &#x3D;&#x3D; 0)
            &#123;
                return &quot;&quot;;
            &#125;
            return str.Substring(0, 1).ToUpper() + str.Substring(1);
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 替换字符串并让它的下一个字母为大写
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;str&quot;&gt;&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;org&quot;&gt;替换字符串&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        public string ReplacAndFirstToUpper(String str, String org)
        &#123;
            String newString &#x3D; &quot;&quot;;
            int first &#x3D; 0;
            while (str.IndexOf(org) !&#x3D; -1)
            &#123;
                first &#x3D; str.IndexOf(org);
                if (first !&#x3D; str.Length)
                &#123;
                    newString &#x3D; newString + str.Substring(0, first);
                    var startIndex &#x3D; first + org.Length;
                    str &#x3D; str.Substring(startIndex, str.Length - startIndex);
                    str &#x3D; FirstToUpper(str);
                &#125;
            &#125;
            newString &#x3D; newString + str;
            return FirstToUpper(newString);
        &#125;
    &#125;
#&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="DBSqlServerSchema-ttinclude"><a href="#DBSqlServerSchema-ttinclude" class="headerlink" title="DBSqlServerSchema.ttinclude"></a>DBSqlServerSchema.ttinclude</h4><p>SqlServer 表信息和列信息的获取</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;#@ assembly name&#x3D;&quot;System.Core&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.xml&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Collections.Generic&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data.SqlClient&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Linq&quot;#&gt;
&lt;#+
    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; SqlServer模式
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public class DBSqlServerSchema : DBCommon, IDBSchema
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 清除的前缀
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        private string _clearPrefix;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 忽略生成的表
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
		private List&lt;string&gt; _ignoreTableList &#x3D; new List&lt;string&gt;();

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 链接字符串
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        private string _connectionString;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 数据库链接对象
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        private SqlConnection _conn;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取表信息sql
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        private string _tableSql &#x3D; @&quot;
SELECT  a.name AS Name ,
        ISNULL(g.[value], &#39;&#39;) AS Remark
FROM    sys.tables a
        LEFT JOIN sys.extended_properties g ON ( a.object_id &#x3D; g.major_id
                                                 AND g.minor_id &#x3D; 0
                                               )
UNION ALL
SELECT  a.name AS Name ,
        &#39;&#39; AS Remark
FROM    sys.views a;&quot;;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取列信息sql
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        private string _columnSql &#x3D; @&quot;
SELECT  d.name TableName ,--表名
        a.colorder AS Colorder ,--字段序号
        a.name AS ColumnName ,--字段名
        ( CASE WHEN COLUMNPROPERTY(a.id, a.name, &#39;IsIdentity&#39;) &#x3D; 1 THEN &#39;true&#39;
               ELSE &#39;false&#39;
          END ) AS IsIdentity ,--标识
        ( CASE WHEN ( SELECT    COUNT(*)
                      FROM      sysobjects--查询主键
                      WHERE     ( name IN (
                                  SELECT    name
                                  FROM      sysindexes
                                  WHERE     ( id &#x3D; a.id )
                                            AND ( indid IN (
                                                  SELECT    indid
                                                  FROM      sysindexkeys
                                                  WHERE     ( id &#x3D; a.id )
                                                            AND ( colid IN (
                                                              SELECT
                                                              colid
                                                              FROM
                                                              syscolumns
                                                              WHERE
                                                              ( id &#x3D; a.id )
                                                              AND ( name &#x3D; a.name ) ) ) ) ) ) )
                                AND ( xtype &#x3D; &#39;PK&#39; )
                    ) &gt; 0 THEN &#39;true&#39;
               ELSE &#39;false&#39;
          END ) AS IsKey ,--查询主键END
        b.name AS SqlType , --类型
        COLUMNPROPERTY(a.id, a.name, &#39;PRECISION&#39;) AS [Length] ,--长度
        ISNULL(COLUMNPROPERTY(a.id, a.name, &#39;Scale&#39;), 0) AS DecimalDigit ,--小数位数
        ( CASE WHEN a.isnullable &#x3D; 1 THEN &#39;true&#39;
               ELSE &#39;false&#39;
          END ) AS IsNull ,--允许空
        ISNULL(e.text, &#39;&#39;) AS DefaultValue ,--默认值
        ISNULL(g.[value], &#39;&#39;) AS Remark--字段说明
FROM    syscolumns a
        LEFT JOIN systypes b ON a.xtype &#x3D; b.xusertype
        INNER JOIN sysobjects d ON a.id &#x3D; d.id
                                   AND d.xtype IN ( &#39;u&#39;, &#39;v&#39; )
                                   AND d.name &lt;&gt; &#39;dtproperties&#39;
        LEFT JOIN syscomments e ON a.cdefault &#x3D; e.id
        LEFT JOIN sys.extended_properties g ON a.id &#x3D; g.major_id
                                               AND a.colid &#x3D; g.minor_id
ORDER BY d.name ,
        a.colorder;&quot;;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 构造函数
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
		&#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;connStr&quot;&gt;链接字符串&lt;&#x2F;param&gt;
		&#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;ignoreTableList&quot;&gt;忽略生成的表&lt;&#x2F;param&gt;
		&#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;clearPrefix&quot;&gt;清除的前缀,默认&#39;tb&#39;，分隔符&#39;_&#39;&lt;&#x2F;param&gt;
        public DBSqlServerSchema(string connStr, List&lt;string&gt; ignoreTableList &#x3D; null, string clearPrefix &#x3D; &quot;tb&quot;)
        &#123;
            _connectionString &#x3D; connStr;
            if(ignoreTableList !&#x3D; null)
            &#123;
                _ignoreTableList &#x3D; ignoreTableList;
            &#125;
            _clearPrefix &#x3D; clearPrefix;
            _conn &#x3D; new SqlConnection(_connectionString);
            _conn.Open();
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 释放资源
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        public void Dispose()
        &#123;
            if (_conn !&#x3D; null)
                _conn.Close();
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取表信息
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        public List&lt;DBTable&gt; GetTableList()
        &#123;
            List&lt;DBTable&gt; dbTableList &#x3D; new List&lt;DBTable&gt;();
            List&lt;DBColumn&gt; allColumnList &#x3D; GetAllColumnList();
            DataTable table &#x3D; null;
            SqlDataAdapter adapter &#x3D; new SqlDataAdapter(_tableSql, _conn);
            table &#x3D; new DataTable();
            adapter.Fill(table);
            if (table !&#x3D; null)
            &#123;
                foreach (DataRow row in table.Rows)
                &#123;
                    &#x2F;&#x2F;忽略的表不生成
                    if (!_ignoreTableList.Contains(row[&quot;Name&quot;].ToString()))
                    &#123;
                        dbTableList.Add(new DBTable()
                        &#123;
                            TableName &#x3D; row[&quot;Name&quot;].ToString(),
                            Name &#x3D; ReplacAndFirstToUpper(
                                    ClearPrefix(row[&quot;Name&quot;].ToString(), _clearPrefix)
                                    , &quot;_&quot;),&#x2F;&#x2F;清除前缀,去除分割符，首字母大写
                            Remark &#x3D; row[&quot;Remark&quot;].ToString(),
                            Columns &#x3D; allColumnList.Where(a &#x3D;&gt; a.TableName &#x3D;&#x3D; row[&quot;Name&quot;].ToString()).ToList()
                        &#125;);
                    &#125;
                &#125;
            &#125;
            return dbTableList;
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取所有列信息
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        private List&lt;DBColumn&gt; GetAllColumnList()
        &#123;
            List&lt;DBColumn&gt; dbCplumnList &#x3D; new List&lt;DBColumn&gt;();
            DataTable table &#x3D; null;
            SqlDataAdapter adapter &#x3D; new SqlDataAdapter(_columnSql, _conn);
            table &#x3D; new DataTable();
            adapter.Fill(table);
            if (table !&#x3D; null)
            &#123;
                foreach (DataRow row in table.Rows)
                &#123;
                    dbCplumnList.Add(new DBColumn()
                    &#123;
                        TableName &#x3D; row[&quot;TableName&quot;].ToString(),
                        ColumnName &#x3D; row[&quot;ColumnName&quot;].ToString(),
                        Name &#x3D; ReplacAndFirstToUpper(row[&quot;ColumnName&quot;].ToString(), &quot;_&quot;),
                        SqlType &#x3D; row[&quot;SqlType&quot;].ToString(),
                        Type &#x3D; TransFromSqlType(row[&quot;SqlType&quot;].ToString(), row[&quot;IsNull&quot;].ToString()),
                        Remark &#x3D; row[&quot;Remark&quot;].ToString(),
                        Colorder &#x3D; int.Parse(row[&quot;Colorder&quot;].ToString()),
                        Length &#x3D; int.Parse(row[&quot;Length&quot;].ToString()),
                        DecimalDigit &#x3D; int.Parse(row[&quot;DecimalDigit&quot;].ToString()),
                        DefaultValue &#x3D; row[&quot;DefaultValue&quot;].ToString(),
                        IsIdentity &#x3D; bool.Parse(row[&quot;IsIdentity&quot;].ToString()),
                        IsNull &#x3D; bool.Parse(row[&quot;IsNull&quot;].ToString()),
                        IsKey &#x3D; bool.Parse(row[&quot;IsKey&quot;].ToString())
                    &#125;);
                &#125;
            &#125;
            return dbCplumnList;
        &#125;

        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; SQL类型转换
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;type&quot;&gt;类型&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;isNull&quot;&gt;是否为空&lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        private string TransFromSqlType(string type, string isNull)
        &#123;
            string typeStr &#x3D; isNull &#x3D;&#x3D; &quot;true&quot; ? &quot;?&quot; : &quot;&quot;;
            switch (type.ToLower())
            &#123;
                case &quot;bigint&quot;: return &quot;long&quot; + typeStr;
                case &quot;binary&quot;: return &quot;byte[]&quot;;
                case &quot;bit&quot;: return &quot;bool&quot; + typeStr;
                case &quot;char&quot;: return &quot;string&quot;;
                case &quot;date&quot;: return &quot;DateTime&quot; + typeStr;
                case &quot;datetime&quot;: return &quot;DateTime&quot; + typeStr;
                case &quot;datetime2&quot;: return &quot;DateTime&quot; + typeStr;
                case &quot;datetimeoffset&quot;: return &quot;string&quot;;
                case &quot;decimal&quot;: return &quot;decimal&quot; + typeStr;
                case &quot;float&quot;: return &quot;double&quot; + typeStr;
                case &quot;geography&quot;: return &quot;byte[]&quot;;
                case &quot;geometry&quot;: return &quot;byte[]&quot;;
                case &quot;hierarchyid&quot;: return &quot;byte[]&quot;;
                case &quot;image&quot;: return &quot;byte[]&quot;;
                case &quot;int&quot;: return &quot;int&quot; + typeStr;
                case &quot;money&quot;: return &quot;decimal&quot; + typeStr;
                case &quot;nchar&quot;: return &quot;string&quot;;
                case &quot;ntext&quot;: return &quot;string&quot;;
                case &quot;numeric&quot;: return &quot;decimal&quot; + typeStr;
                case &quot;nvarchar&quot;: return &quot;string&quot;;
                case &quot;real&quot;: return &quot;float&quot;;
                case &quot;smalldatetime&quot;: return &quot;DateTime&quot; + typeStr;
                case &quot;smallint&quot;: return &quot;short&quot; + typeStr;
                case &quot;smallmoney&quot;: return &quot;decimal&quot; + typeStr;
                case &quot;sql_variant&quot;: return &quot;object&quot;;
                case &quot;text&quot;: return &quot;string&quot;;
                case &quot;time&quot;: return &quot;string&quot;;
                case &quot;timestamp&quot;: return &quot;byte[]&quot;;
                case &quot;tinyint&quot;: return &quot;byte&quot; + typeStr;
                case &quot;uniqueidentifier&quot;: return &quot;Guid&quot; + typeStr;
                case &quot;varbinary&quot;: return &quot;byte[]&quot;;
                case &quot;varchar&quot;: return &quot;string&quot;;
                case &quot;xml&quot;: return &quot;string&quot;;
                default: return &quot;object&quot;;
            &#125;
        &#125;
    &#125;
#&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="MultiDocument-ttinclude"><a href="#MultiDocument-ttinclude" class="headerlink" title="MultiDocument.ttinclude"></a>MultiDocument.ttinclude</h4><p>用于 T4 文件分割</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;#@ assembly name&#x3D;&quot;System.Core&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;EnvDTE&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Collections.Generic&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.IO&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Text&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;Microsoft.VisualStudio.TextTemplating&quot;#&gt;
&lt;#+
&#x2F;&#x2F;&#x2F; &lt;summary&gt;
&#x2F;&#x2F;&#x2F; T4 模板分割文件辅助类
&#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
class Manager
&#123;
    public struct Block &#123;
        public String Name;
        public int Start, Length;
    &#125;

    public List&lt;Block&gt; blocks &#x3D; new List&lt;Block&gt;();
    public Block currentBlock;
    public Block footerBlock &#x3D; new Block();
    public Block headerBlock &#x3D; new Block();
    public ITextTemplatingEngineHost host;
    public ManagementStrategy strategy;
    public StringBuilder template;
    public String OutputPath &#123; get; set; &#125;

    public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) &#123;
        this.host &#x3D; host;
        this.template &#x3D; template;
        OutputPath &#x3D; String.Empty;
        strategy &#x3D; ManagementStrategy.Create(host);
    &#125;

    public void StartBlock(String name) &#123;
        currentBlock &#x3D; new Block &#123; Name &#x3D; name, Start &#x3D; template.Length &#125;;
    &#125;

    public void StartFooter() &#123;
        footerBlock.Start &#x3D; template.Length;
    &#125;

    public void EndFooter() &#123;
        footerBlock.Length &#x3D; template.Length - footerBlock.Start;
    &#125;

    public void StartHeader() &#123;
        headerBlock.Start &#x3D; template.Length;
    &#125;

    public void EndHeader() &#123;
        headerBlock.Length &#x3D; template.Length - headerBlock.Start;
    &#125;

    public void EndBlock() &#123;
        currentBlock.Length &#x3D; template.Length - currentBlock.Start;
        blocks.Add(currentBlock);
    &#125;

    public void Process(bool split) &#123;
        String header &#x3D; template.ToString(headerBlock.Start, headerBlock.Length);
        String footer &#x3D; template.ToString(footerBlock.Start, footerBlock.Length);
        blocks.Reverse();
        foreach(Block block in blocks) &#123;
            String fileName &#x3D; Path.Combine(OutputPath, block.Name);
            if (split) &#123;
                String content &#x3D; header + template.ToString(block.Start, block.Length) + footer;
                strategy.CreateFile(fileName, content);
                template.Remove(block.Start, block.Length);
            &#125; else &#123;
                strategy.DeleteFile(fileName);
            &#125;
        &#125;
    &#125;
&#125;

class ManagementStrategy
&#123;
    internal static ManagementStrategy Create(ITextTemplatingEngineHost host) &#123;
        return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host);
    &#125;

    internal ManagementStrategy(ITextTemplatingEngineHost host) &#123; &#125;

    internal virtual void CreateFile(String fileName, String content) &#123;
        File.WriteAllText(fileName, content);
    &#125;

    internal virtual void DeleteFile(String fileName) &#123;
        if (File.Exists(fileName))
            File.Delete(fileName);
    &#125;
&#125;

class VSManagementStrategy : ManagementStrategy
&#123;
    private EnvDTE.ProjectItem templateProjectItem;

    internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) &#123;
        IServiceProvider hostServiceProvider &#x3D; (IServiceProvider)host;
        if (hostServiceProvider &#x3D;&#x3D; null)
            throw new ArgumentNullException(&quot;Could not obtain hostServiceProvider&quot;);

        EnvDTE.DTE dte &#x3D; (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
        if (dte &#x3D;&#x3D; null)
            throw new ArgumentNullException(&quot;Could not obtain DTE from host&quot;);

        templateProjectItem &#x3D; dte.Solution.FindProjectItem(host.TemplateFile);
    &#125;

    internal override void CreateFile(String fileName, String content) &#123;
        base.CreateFile(fileName, content);
        ((EventHandler)delegate &#123; templateProjectItem.ProjectItems.AddFromFile(fileName); &#125;).BeginInvoke(null, null, null, null);
    &#125;

    internal override void DeleteFile(String fileName) &#123;
        ((EventHandler)delegate &#123; FindAndDeleteFile(fileName); &#125;).BeginInvoke(null, null, null, null);
    &#125;

    private void FindAndDeleteFile(String fileName) &#123;
        foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) &#123;
            if (projectItem.get_FileNames(0) &#x3D;&#x3D; fileName) &#123;
                projectItem.Delete();
                return;
            &#125;
        &#125;
    &#125;
&#125;#&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="DBSchemaFactory-ttinclude"><a href="#DBSchemaFactory-ttinclude" class="headerlink" title="DBSchemaFactory.ttinclude"></a>DBSchemaFactory.ttinclude</h4><p>数据库模式工厂，记得修改相应的连接字符串、忽略的表名、前缀</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;#@ assembly name&#x3D;&quot;System.Core&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ assembly name&#x3D;&quot;System.xml&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Collections.Generic&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Data.SqlClient&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Linq&quot;#&gt;
&lt;#@ include file&#x3D;&quot;DBCommon.ttinclude&quot;#&gt;
&lt;#@ include file&#x3D;&quot;DBSqlServerSchema.ttinclude&quot;#&gt;
&lt;#@ include file&#x3D;&quot;MultiDocument.ttinclude&quot;#&gt;
&lt;#+
    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 数据库模式工厂
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
	public class DBSchemaFactory
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取数据库信息
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;param name&#x3D;&quot;DatabaseType&quot;&gt;数据库类型：SqlServer &lt;&#x2F;param&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        public static List&lt;DBTable&gt; GetTableList(DBType type)
        &#123;
            IDBSchema dbSchema;
            switch (type)
            &#123;
                case DBType.SqlServer:
                    dbSchema &#x3D; new DBSqlServerSchema(&quot;server&#x3D;.;database&#x3D;Demo;uid&#x3D;sa;pwd&#x3D;123456;&quot;, new List&lt;string&gt;()&#123; &quot;忽略的表名&quot; &#125;, &quot;tb&quot;);
                    break;
                default:
                    throw new ArgumentException(&quot;The input argument of DatabaseType is invalid!&quot;);
            &#125;
            List&lt;DBTable&gt; tbList &#x3D; dbSchema.GetTableList();
            dbSchema.Dispose();&#x2F;&#x2F;释放数据库链接资源
            return tbList;
        &#125;
    &#125;

    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 数据库模式接口
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public interface IDBSchema : IDisposable
    &#123;
        &#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; 获取表信息
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;returns&gt;&lt;&#x2F;returns&gt;
        List&lt;DBTable&gt; GetTableList();
    &#125;

    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; 数据库类型
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
    public enum DBType
    &#123;
        SqlServer &#x3D; 1,
        MySql &#x3D; 2
    &#125;
#&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="Models-tt"><a href="#Models-tt" class="headerlink" title="Models.tt"></a>Models.tt</h4><p>根据数据库表和列信息，生成 EF 实体</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;#@ template debug&#x3D;&quot;true&quot; hostspecific&#x3D;&quot;true&quot; language&#x3D;&quot;C#&quot;  #&gt;
&lt;#@ output extension&#x3D;&quot;.cs&quot; #&gt;
&lt;#@ assembly name&#x3D;&quot;System.Core&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System&quot;#&gt;
&lt;#@ import namespace&#x3D;&quot;System.Collections.Generic&quot;#&gt;
&lt;#@ include file&#x3D;&quot;..&#x2F;T4Code&#x2F;DBSchemaFactory.ttinclude&quot;#&gt;
&lt;#
    var manager &#x3D; new Manager(Host, GenerationEnvironment, true) &#123; OutputPath &#x3D; Path.GetDirectoryName(Host.TemplateFile)&#125;;
    List&lt;DBTable&gt; tableList&#x3D;DBSchemaFactory.GetTableList(DBType.SqlServer);
    foreach(DBTable t in tableList)
    &#123;
		&#x2F;&#x2F;分割文件开始
        manager.StartBlock(t.Name+&quot;.cs&quot;);
#&gt;
&#x2F;&#x2F;------------------------------------------------------------------------------
&#x2F;&#x2F;     此代码由T4模板自动生成
&#x2F;&#x2F;     对此文件的更改可能会导致不正确的行为，并且如果
&#x2F;&#x2F;     重新生成代码，这些更改将会丢失。
&#x2F;&#x2F;------------------------------------------------------------------------------

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace T4.Model
&#123;

    &#x2F;&#x2F;&#x2F; &lt;summary&gt;
    &#x2F;&#x2F;&#x2F; &lt;#&#x3D;t.Remark#&gt;
    &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
	[Table(&quot;&lt;#&#x3D;t.TableName#&gt;&quot;)]
    public class &lt;#&#x3D;t.Name#&gt;
    &#123;

&lt;#
		int colorder &#x3D; 0;&#x2F;&#x2F;主键顺序
        foreach(DBColumn c in t.Columns)
        &#123;
#&gt;
		&#x2F;&#x2F;&#x2F; &lt;summary&gt;
        &#x2F;&#x2F;&#x2F; &lt;#&#x3D;c.Remark#&gt;
        &#x2F;&#x2F;&#x2F; &lt;&#x2F;summary&gt;
        &lt;#&#x3D;c.IsIdentity?&quot;[DatabaseGenerated(DatabaseGeneratedOption.Identity)]&quot;:&quot;&quot;#&gt;
&lt;#
            if (c.IsKey)
            &#123;
#&gt;
		[Key, Column(&quot;&lt;#&#x3D;c.ColumnName#&gt;&quot;, TypeName &#x3D; &quot;&lt;#&#x3D;c.SqlType#&gt;&quot;, Order &#x3D; &lt;#&#x3D;colorder#&gt;)]
&lt;#
				colorder++;
            &#125;
			else
			&#123;
#&gt;
		[Column(&quot;&lt;#&#x3D;c.ColumnName#&gt;&quot;, TypeName &#x3D; &quot;&lt;#&#x3D;c.SqlType#&gt;&quot;)]
&lt;#
            &#125;
#&gt;
        public &lt;#&#x3D;c.Type#&gt; &lt;#&#x3D;c.Name#&gt; &#123; get; set; &#125;
&lt;#
        &#125;
#&gt;
    &#125;
&#125;
&lt;#
		&#x2F;&#x2F;分割文件结束
        manager.EndBlock();
    &#125;

    manager.Process(true);
#&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="实现效果"><a href="#实现效果" class="headerlink" title="实现效果"></a>实现效果</h4><p>Models.tt 文件每次保存，都会重新执行一次模板引擎，所以生成的实体文件最好不要手动修改。</p>
<p><img src="/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/%E4%BB%A3%E7%A0%81%E6%95%88%E6%9E%9C.png" alt="项目目录"></p>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><ol>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/dataadapter/p/3844394.html">用 T4 Template 生成代码</a></li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/lzrabbit/archive/2012/07/15/2591085.html">T4 模版引擎之基础入门</a></li>
<li><a target="_blank" rel="noopener" href="https://docs.microsoft.com/zh-cn/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2015">代码生成和 T4 文本模板</a></li>
</ol>
<h3 id="项目源码"><a href="#项目源码" class="headerlink" title="项目源码"></a>项目源码</h3><p><a href="/downloads/T4.zip">点击下载</a></p>

            <div class="post-copyright">
    <div class="content">
        <p>最后更新： 2021年04月07日 16:16</p>
        <p>原始链接： <a class="post-url" href="/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/" title="T4模版生成EF实体">http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/</a></p>
        <footer>
            <a href="http://jiangkunyun.gitee.io">
                <img src="/images/mylogo.png" alt="jiangkunyun">
                jiangkunyun
            </a>
        </footer>
    </div>
</div>

      
        
            
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;">赏</a>
</div>

<div id="reward" class="post-modal reward-lay">
    <a class="close" href="javascript:;" id="reward-close">×</a>
    <span class="reward-title">
        <i class="icon icon-quote-left"></i>
        请我吃糖~
        <i class="icon icon-quote-right"></i>
    </span>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/images/wechat.jpg" alt="打赏二维码">
        </div>
        <div class="reward-select">
            
            <label class="reward-select-item checked" data-id="wechat" data-wechat="/images/wechat.jpg">
                <img class="reward-select-item-wechat" src="/images/wechat.png" alt="微信">
            </label>
            
            
            <label class="reward-select-item" data-id="alipay" data-alipay="/images/alipay.jpg">
                <img class="reward-select-item-alipay" src="/images/alipay.png" alt="支付宝">
            </label>
            
        </div>
    </div>
</div>


        
    </div>
    <footer class="article-footer">
        
        
<div class="post-share">
    <a href="javascript:;" id="share-sub" class="post-share-fab">
        <i class="fa fa-share-alt"></i>
    </a>
    <div class="post-share-list" id="share-list">
        <ul class="share-icons">
          <li>
            <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/&title=《T4模版生成EF实体》 — JiangKunYun's Blog&pic=http://jiangkunyun.gitee.ioimages/mylogo.png" data-title="微博">
              <i class="fa fa-weibo"></i>
            </a>
          </li>
          <li>
            <a class="weixin share-sns" id="wxFab" href="javascript:;" data-title="微信">
              <i class="fa fa-weixin"></i>
            </a>
          </li>
          <li>
            <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/&title=《T4模版生成EF实体》 — JiangKunYun's Blog&source=T4(Text Template Transformation Toolkit)是微软官方在 VisualStudio 2008 中开始使用的代码生成引擎..." data-title="QQ">
              <i class="fa fa-qq"></i>
            </a>
          </li>
          <li>
            <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/" data-title="Facebook">
              <i class="fa fa-facebook"></i>
            </a>
          </li>
          <li>
            <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《T4模版生成EF实体》 — JiangKunYun's Blog&url=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/&via=http://jiangkunyun.gitee.io" data-title="Twitter">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li>
            <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/" data-title="Google+">
              <i class="fa fa-google-plus"></i>
            </a>
          </li>
        </ul>
     </div>
</div>
<div class="post-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;" id="wxShare-close">×</a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://jiangkunyun.gitee.io/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/T4%E6%A8%A1%E7%89%88%E7%94%9F%E6%88%90EF%E5%AE%9E%E4%BD%93/" alt="微信分享二维码">
</div>

<div class="mask"></div>

        
        <ul class="article-footer-menu">
            
            
  <li class="article-footer-tags">
    <i class="fa fa-tags"></i>
      
    <a href="/tags/T4/" class="color3">T4</a>
      
    <a href="/tags/EF/" class="color3">EF</a>
      
  </li>

        </ul>
        
    </footer>
  </div>
</article>


    <aside class="post-toc-pos post-toc-top" id="post-toc">
        <nav class="post-toc-wrap">
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#T4-%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E%E4%B9%8B%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8"><span class="post-toc-text">T4 模版引擎之基础入门</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#T4-%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90-EF-%E5%AE%9E%E4%BD%93"><span class="post-toc-text">T4 代码生成 EF 实体</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#%E9%A1%B9%E7%9B%AE%E7%BB%93%E6%9E%84"><span class="post-toc-text">项目结构</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#DBCommon-ttinclude"><span class="post-toc-text">DBCommon.ttinclude</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#DBSqlServerSchema-ttinclude"><span class="post-toc-text">DBSqlServerSchema.ttinclude</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#MultiDocument-ttinclude"><span class="post-toc-text">MultiDocument.ttinclude</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#DBSchemaFactory-ttinclude"><span class="post-toc-text">DBSchemaFactory.ttinclude</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Models-tt"><span class="post-toc-text">Models.tt</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#%E5%AE%9E%E7%8E%B0%E6%95%88%E6%9E%9C"><span class="post-toc-text">实现效果</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="post-toc-text">参考资料</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81"><span class="post-toc-text">项目源码</span></a></li></ol>
        </nav>
    </aside>
    

<nav id="article-nav">
  
    <a href="/git/VS2019/Visual-Studio-2019-%E4%BD%BF%E7%94%A8-Git/" id="article-nav-newer" class="article-nav-link-wrap">

      <span class="article-nav-title">
        <i class="fa fa-hand-o-left" aria-hidden="true"></i>
        
          Visual Studio 2019 使用 Git
        
      </span>
    </a>
  
  
</nav>



    
        <div id="SOHUCS" sid="T4模版生成EF实体" ></div>
<script type="text/javascript">
    (function(){
        var appid = 'cyvoqiokX';
        var conf = '54b1085fb6291057e24803fe79916138';
        var width = window.innerWidth || document.documentElement.clientWidth;
        if (width < 960) {
            window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    
</section>
        
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info" class="inner">
      
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


      <p>
        Powered by  <a href="http://hexo.io/" target="_blank">Hexo</a>
        Theme <a href="//github.com/wongminho/hexo-theme-miho" target="_blank">MiHo</a>
      &copy; 2021 jiangkunyun<br>
      </p>
    </div>
  </div>
</footer>
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  var mihoConfig = {
      root: "http://jiangkunyun.gitee.io",
      animate: true,
      isHome: false,
      share: true,
      reward: 1
  }
</script>
<div class="sidebar">
    <div id="sidebar-search" title="Search">
        <i class="fa fa-search"></i>
    </div>
    <div id="sidebar-category" title="Categories">
        <i class="fa fa-book"></i>
    </div>
    <div id="sidebar-tag" title="Tags">
        <i class="fa fa-tags"></i>
    </div>
    <div id="sidebar-top">
        <span class="sidebar-top-icon"><i class="fa fa-angle-up"></i></span>
    </div>
</div>
<div class="sidebar-menu-box" id="sidebar-menu-box">
    <div class="sidebar-menu-box-container">
        <div id="sidebar-menu-box-categories">
            <a class="category-link" href="/categories/git/">git</a><a class="category-link" href="/categories/git/VS2019/">VS2019</a><a class="category-link" href="/categories/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/">模版引擎</a><a class="category-link" href="/categories/%E6%A8%A1%E7%89%88%E5%BC%95%E6%93%8E/T4/">T4</a>
        </div>
        <div id="sidebar-menu-box-tags">
            <a href="/tags/EF/" style="font-size: 10px;">EF</a> <a href="/tags/T4/" style="font-size: 10px;">T4</a> <a href="/tags/VS2019/" style="font-size: 10px;">VS2019</a> <a href="/tags/git/" style="font-size: 10px;">git</a>
        </div>
    </div>
    <a href="javascript:;" class="sidebar-menu-box-close">&times;</a>
</div>
<div class="mobile-header-menu-nav" id="mobile-header-menu-nav">
    <div class="mobile-header-menu-container">
        <span class="title">Menus</span>
        <ul class="mobile-header-menu-navbar">
            
            <li>
                <a  href="/">
                    <i class="fa fa-home"></i><span>首页</span>
                </a>
            </li>
            
            <li>
                <a  href="/archives">
                    <i class="fa fa-archive"></i><span>归档</span>
                </a>
            </li>
            
            <li>
                <a  href="/about">
                    <i class="fa fa-user"></i><span>关于</span>
                </a>
            </li>
            
        </ul>
    </div>
    <div class="mobile-header-tag-container">
        <span class="title">Tags</span>
        <div id="mobile-header-container-tags">
            <a href="/tags/EF/" style="font-size: 10px;">EF</a> <a href="/tags/T4/" style="font-size: 10px;">T4</a> <a href="/tags/VS2019/" style="font-size: 10px;">VS2019</a> <a href="/tags/git/" style="font-size: 10px;">git</a>
        </div>
    </div>
</div>
<div class="search-wrap">
    <span class="search-close">&times;</span>
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
            <i class="icon icon-lg icon-chevron-left"></i>
        </a>
        <input class="search-field" placeholder="Search..." id="keywords">
        <a id="search-submit" href="javascript:;">
            <i class="fa fa-search"></i>
        </a>
    <div class="search-container" id="search-container">
        <ul class="search-result" id="search-result">
        </ul>
    </div>
</div>

<div id="search-tpl">
    <li class="search-result-item">
        <a href="{url}" class="search-item-li">
            <span class="search-item-li-title" title="{title}">{title}</span>
        </a>
    </li>
</div>

<script src="/js/search.js"></script>


<script src="/js/main.js"></script>



  <script src="//cdn.bootcss.com/particles.js/2.0.0/particles.min.js"></script>
  <div id="particles"></div>
  
<script src="/js/particles.js"></script>








  
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">

  <script src="//cdn.bootcss.com/scrollReveal.js/3.0.5/scrollreveal.js"></script>
  
<script src="/js/animate.js"></script>



  
<script src="/js/pop-img.js"></script>

  <script>
     $(".article-entry p img").popImg();
  </script>

  </div>
</body>
</html>